/*
 * @Author: wwssaabb
 * @Date: 2021-11-23 09:37:11
 * @LastEditTime: 2021-12-13 08:51:55
 * @FilePath: \handwritten-code\array\reduce.js
 */

//实现 reduce

Array.prototype.myReduce = function (executor, initialValue) {
  if (this == null) return new TypeError('this is null or undefined')
  if (typeof executor !== 'function') return new TypeError(`${executor} must be a function`)

  let res = initialValue ? initialValue : this[0]
  for (let i = initialValue ? 0 : 1; i < this.length; i++) {
    res = executor(res, this[i], i, this)
  }
  return res
}

let a = [{
  name: 'zs',
  age: 10
}, {
  name: 'ls',
  age: 12
}, {
  name: 'ww',
  age: 13
}, {
  name: 'll',
  age: 17
}, {
  name: 'sb',
  age: 20
}]

console.log(a.myReduce((p, c) => p += c.age))
console.log(a.reduce((p, c) => p += c.age))
console.log('-----------')
console.log(a.myReduce((p, c) => p += c.name))
console.log(a.reduce((p, c) => p += c.name))